package modules

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"gspeed/bootstrap/global"
	"time"
)

type mongoClient struct {
	client *mongo.Client
}

var MongoDB mongoClient

func (m *mongoClient) New() *mongo.Client {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// mongo配置
	option := options.Client().ApplyURI(m.getURI())

	// 连接mongo
	var err error
	m.client, err = mongo.Connect(ctx, option)
	if err != nil {
		global.Logger.Errorf("connect to mongodb error: %v", err)
	}
	// 测试
	m.ping()
	return m.client
}

func (m *mongoClient) getURI() string {
	// 设置默认值
	global.Config.SetDefault("mongo.host", "localhost")
	global.Config.SetDefault("mongo.port", 27017)
	global.Config.SetDefault("mongo.username", "")
	global.Config.SetDefault("mongo.password", "")

	// 读取配置
	username := global.Config.GetString("mongo.username")
	password := global.Config.GetString("mongo.password")
	auth := ""
	if username != "" && password == "" {
		auth = username + "@"
	}
	if username != "" && password != "" {
		auth = username + ":" + password + "@"
	}
	return fmt.Sprintf("mongodb://%s%s:%d",
		auth,
		global.Config.GetString("mongo.host"),
		global.Config.GetInt("mongo.port"),
	)

}

func (m *mongoClient) ping() {
	// 检查连接
	err := m.client.Ping(context.TODO(), readpref.Primary())
	if err != nil {
		global.Logger.Errorf("check the connection to mongo error: %v", err)
	}
}

func (m *mongoClient) Close() {

	if err := m.client.Disconnect(context.TODO()); err != nil {
		panic(err)
		return
	}
	fmt.Println("connection to MongoDB closed.")
}
